/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;

/**
 *
 * @author Stefano
 */
@Stateless
@LocalBean
public class SponsorUserManager {
    @EJB
    private SponsorUserFacade sponsorUserFacade;

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    public void addSponsorUser(String uid, int credit) {
        SponsorUser suser = new SponsorUser();
        suser.setUserID(uid);
        suser.setCredit(credit);
        sponsorUserFacade.create(suser);
    }
    
    public boolean isNewUser(String uid) {
        List<SponsorUser> users = sponsorUserFacade.findAll();
        for(SponsorUser found:users){
            if (found.getUserID().equals(uid))
                return false;    
        }
        return true;
    }

    public SponsorUser findSponsorUser(String uid) {
        List<SponsorUser> users = sponsorUserFacade.findAll();
        for(SponsorUser found:users){
            if (found.getUserID().equals(uid))
                return found;    
        }
        return null;
    }  
    
//    public void decrementCredit(String uid){
//        SponsorUser suser = findSponsorUser(uid);
//        int credit = suser.getCredit();
//        credit = credit -1;
//        suser.setCredit(credit);
//        sponsorUserFacade.edit(suser);
//    }
    
    public void rechargeCredit(String uid, int recharge){
        SponsorUser suser = findSponsorUser(uid);
        int newCredit = suser.getCredit() + recharge;
        suser.setCredit(newCredit);
        sponsorUserFacade.edit(suser);
    }
    
    public void payCredit(String uid, int dec){
        SponsorUser suser = findSponsorUser(uid);
        int newCredit;
        if((suser.getCredit() - dec) >=0)
            newCredit = suser.getCredit() - dec;
        else
            newCredit = 0;
        suser.setCredit(newCredit);
        sponsorUserFacade.edit(suser);
    }
    
    public boolean isNewSponsorUser(String uid) {
        List<SponsorUser> susers = sponsorUserFacade.findAll();
        for(SponsorUser found: susers){
            if (found.getUserID().equals(uid))
                return false;
        }
        return true;
    }
    
}
